<script lang="ts" setup>
import { ref, reactive, onMounted, shallowRef, watch, toRaw } from 'vue'
import {
  NSpace,
  NButton,
  type FormInst,
  NFormItem,
  NInput,
  NSelect,
  useMessage,
  NScrollbar,
  NSpin,
  NDataTable,
  NForm,
  NImageGroup,
  NImage,
  type SelectOption,
  NTooltip,
  type DataTableColumns
} from 'naive-ui'
import { sendRequest } from '@/utils/api'
import FixedAction from '@/components/FixedAction.vue'
import { keysOf } from '@/utils/object'
import { useRoute } from 'vue-router'
import { mergeWith, isArray } from 'lodash-es'
import DynamicPageForm from '@/components/DynamicPageForm/DynamicPageForm.vue'
import type { ModelJson } from '@/components/DynamicPageForm/DynamicFormTypes'
import VDisOrEnd from '@/views/OA/Common/DisOrEnd.vue'
import useSubmit,{defaultVersionTypeValue,defaultVersionTypeKey} from '@/components/DynamicFormComponent/useSubmit'
import DynamicFormComponent from '@/components/DynamicFormComponent/index.vue'
import useRouteReplace from '@/hooks/useRouteReplace'
const { dfInst, formData:formData1, createVars,submitLoading,submit:submitR } = useSubmit()
const props = defineProps({
  id: { type: String, default: () => null },
  typeShow: { type: Number, default: () => 0 },
  code: { type: String, default: () => null },
  idSelf: { type: String, default: () => null }
})
const isUpdate = false
const isDetail = true
const tableData1 = ref()
const route = useRoute()
const routeReplace = useRouteReplace(route.query.redirect as string)

const array = props?.id?.split(',') || []
const message = useMessage()
const userFormRef = ref<FormInst | null>(null)
const loading = ref(false)
const form: any = reactive({
  id: array?.[0],
  password: array?.[0] ? null : 'Aa123456!',
  userStatus: 1,
  typeTree: null,
  typeTreeS: null,
  typeTreeT: null,
  time: null,
  name: null,
  repactName: null,
  collectName: null,
  phone: null,
  person: null,
  dujiaoName: null,
  Uptime: null,
  price: null,
  author: null,
  number1: null,
  yesNO: null,
  yinciTime: null,
  remack: null,
  ziicaCode: null,
  serialNumber: null,
  position: null,
  itemsStaging: {
    assetCode: null,
    firstLevelCode: null,
    threeLevelCode: null,
    secondLevelCode: null,
    fifthLevelCode: null,
    fourthLevelCode: null,
    serialNumber: null
  }
})
const oneSelectValue = ref<string | null>(null)
const oneSelectOptions = shallowRef<[]>([])
const oneSelectLoading = ref(false)

const twoSelectValue = ref<string | null>(null)
const twoSelectOptions = shallowRef<[]>([])
const twoSelectLoading = ref(false)

const threeSelectValue = ref<string | null>(null)
const threeSelectOptions = shallowRef<[]>([])
const threeSelectLoading = ref(false)

const isUseLastSelect = ref(true)
const clueMethodOptions: any = reactive([])
const formInst = ref<FormInst | null>(null)
// const formData = ref({} as any)
const modelJson = ref({} as ModelJson)
const queryJsonBM = async (code: string) => {
  try {
    const [error, res]: any = await sendRequest({
      module: 'collection',
      api: 'jsonContent',
      override: {
        params: {
          name: `BM_${code}.json`
        }
      }
    })
    if (error) throw error
    if (res.code !== 200) throw new Error(res.message)
    otherJson.value = res.data
  } catch (error) {
    console.error(error)
  }
}
const queryJson = async (code: string) => {
  try {
    const [error, res]: any = await sendRequest({
      module: 'collection',
      api: 'jsonContent',
      override: {
        params: {
          name: `${code}.json`
        }
      }
    })
    if (error) throw error
    if (res.code !== 200) throw new Error(res.message)
    modelJson.value = res.data
    return res.data
  } catch (error) {
    console.error(error)
  }
}
const fileImgList:any = ref([])//附件数组
const baseModel: ModelJson = {
  elements: [
    {
      type: 'NInput',
      key: 'itemName',
      label: '名称：',
      rule: {
        required: true,
        message: '名称必填'
      }
    },
    {
      type: 'NDatePicker',
      key: 'receiveTime',
      label: '接收时间：',
      props: { type: 'datetime', format: 'yyyy-MM-dd HH:mm:ss' },
      style: { flex: 1 },
      rule: {
        required: true,
        message: '接收时间必填'
      }
    },
    {
      type: 'NSelect',
      key: 'collectTypeCode',
      label: '征集方式：',
      props: {
        options: clueMethodOptions,
        valueField: 'code',
        labelField: 'name'
      },
      rule: {
        required: true,
        message: '征集方式必填'
      }
    },
    {
      type: 'NInputNumber',
      key: 'itemNum',
      label: '数量：',
      style: { flex: 1 },
      props: {
        showButton: false,
        min: 0
      },
      rule: {
        type: 'number',
        required: true,
        message: '数量必填'
      }
    },
    {
      type: 'NInput',
      key: 'receiveUser',
      label: '接收人：',
      rule: {
        required: true,
        message: '接收人必填'
      }
    },
    {
      type: 'NInput',
      key: 'notes',
      label: '备注：',
      props: {
        type: 'textarea',
        rows: 1
      },
      rule: {
        required: true,
        message: '备注必填'
      }
    }
  ]
}
// const model = shallowRef<any>(baseModel)
// const setModelJson = async (code?: string | null) => {
//   if (!code) return (model.value = toRaw(baseModel))
//   model.value = mergeWith({}, toRaw(baseModel), await queryJson(code), (obj: any, src: any) => {
//     if (isArray(obj)) return [...obj, ...src]
//   }) as ModelJson
// }
const clueInfoLoading = ref(false)
const checkIsDetail = async (code: any) => {
  
  try {
    const [error, res] = await sendRequest({
      module: 'collectProcess',
      api: 'info',
      uri: {
        itemCode: code as string
      }
    })
    if (error) throw error
    if (res.code !== 0) throw new Error(res.msg)
    // await setModelJson(res.data.itemTypeCode)
    const { data } = res
   
    // formData.value = Object.assign(
    //   {},
    //   {
    //     itemName: data.itemName,
    //     receiveTime: data.receiveTime,
    //     itemTypeCode: data.itemTypeCode,
    //     itemTypeName: data.itemTypeName,
    //     collectTypeName: data.collectTypeName,
    //     itemNum: data.itemNum,
    //     receiveUser: data.receiveUser,
    //     notes: data.notes,
    //     itemTypeItem: data.itemTypeName
    //   },
    //   JSON.parse(data.jsonStr || '{}')
    // )
    // fileList.value = data.fileList?.map((e: any, i: number) => ({
    //   id: i,
    //   name: e.name,
    //   status: 'finished',
    //   url: e.path,
    //   remoteId: e.id
    // }))
  } catch (error) {
    console.error(error)
  } finally {
    setTimeout(() => {
      clueInfoLoading.value = false
    }, 2000)
  }
}
// 返回
const goBack = () => {
  // history.back()
  routeReplace()
}
const otherJson = ref({} as ModelJson)

// const queryTypeJson = async (type: string): Promise<any> => {
//   return await (await fetch(`/form-models/${type}.json`)).json()
// }
// watch(
//   () => formData.value.type,
//   async (type) => {
//     if (!type) return (model.value = baseModel)
//     model.value = mergeWith({}, baseModel, await queryTypeJson(type), (obj: any, src: any) => {
//       if (isArray(obj)) return [...obj, ...src]
//     })
//   },
//   { immediate: true }
// )
const endBackShow = ref(false)
const inputShow = ref(false)
const GroupList = ref() //套组
// const formData1 = ref()
const getInfo = async () => {
  sendRequest({
    module: 'collectProcess',
    api: 'catalogInfo',
    uri: {
      subItemCode: props.id
    }
  }).then(async ([err, res]) => {
    if (err) return

    keysOf(res.data.detailVo).forEach((e) => {
      form[e] = res.data[e] as never
    })
    endBackShow.value = res.data.collectingItems?.assessStatusCode == 'A5004' ? true : false
    console.log(res.data)
    inputShow.value =
      res.data.collectingItems?.assessStatusCode == 'A5007' &&
        res.data.collectingItems?.collectionStatusCode == 'A4701'
        ? true
        : false
    GroupList.value = (res.data?.itemsStagingList ? res.data?.itemsStagingList : []).concat({
      ...res.data?.itemsStaging
    })
    fileImgList.value = []
    res.data?.collectingItems?.fileList?.map((i: any) => {
      fileImgList.value.push({
        name: i.name,
        url: i.path,
        status: 'finished',
        id: i.id
      })
    })
    form.itemsStaging.subItemCode = res.data?.subItemCode || null
    form.itemsStaging.assetCode =
      res.data?.itemsStaging?.assetCode || res.data?.itemsStaging?.assetCode == 0
        ? res.data?.itemsStaging?.assetCode
        : null
    form.itemsStaging.firstLevelCode = res.data?.itemsStaging?.firstLevelName || null
    form.itemsStaging.secondLevelCode = res.data?.itemsStaging?.secondLevelName || null
    form.itemsStaging.threeLevelCode = res.data?.itemsStaging?.threeLevelName || null
    form.itemsStaging.fourthLevelCode = res.data?.itemsStaging?.fourthLevelName || null
    form.itemsStaging.fifthLevelCode = res.data?.itemsStaging?.fifthLevelName || null
    form.itemsStaging.sixthLevelCode = res.data?.itemsStaging?.sixthLevelName || null
    // queryJsonBM(res.data?.detailVo?.itemTypeCode)
    
    
    checkIsDetail(res.data?.detailVo?.itemCode)
    formData1.value = JSON.parse(res.data?.catalogInfo || `{"${defaultVersionTypeKey}": "${defaultVersionTypeValue}" }`)
    if (formData1.value['BMCOM006']) formData1.value['BMCOM006'] = formData1.value['BMCOM006'].split('>').pop()
  })
}
const showStart = ref(false)
const showEnd = ref(false)
const tableData2 = ref()
const getFlowFn1 = () => {
  sendRequest({
    module: 'collectProcess',
    api: 'infoFinalAuditRecord',
    uri: {
      subItemCode: props?.id
    }
  }).then(async ([err, res]) => {
    if (err) return
    form.status = res.data[0]?.status
    form.workflow = res.data[0]?.workflow
    tableData1.value = res.data[0]?.approvalRecordsList || []
    form.status1 = res.data[1]?.status
    form.workflow1 = res.data[1]?.workflow
    tableData2.value = res.data[1]?.approvalRecordsList || []
    if (res.data?.length == 2) {
      showStart.value = true
      showEnd.value = true
    } else if (res.data?.length == 1) {
      showStart.value = true
      showEnd.value = false
    } else {
      showStart.value = false
      showEnd.value = false
    }
    form.assigneeFlag = res.data[0]?.assigneeFlag
    form.fromId = res.data?.pop()?.fromId
  })
}
// const getFlowFn = () => {
//   sendRequest({
//     module: 'collectProcess',
//     api: 'infoAuditRecord',
//    uri:{
//     subItemCode: props?.id
//    }

//   }).then(async ([err, res]) => {
//     if (err) return
//     keysOf(res.data).forEach((e) => {
//       form[e] = res.data[e] as never
//     })
//     tableData1.value = res.data?.approvalRecordsList || []
//   })
// }
const showLoading = ref(false)
// watch(
//   () => route,
//   () => {
//     if(route.name=='selfdetailMakeMenu')
//     {
//       if (props.id) {
//       showLoading.value = true
//       getFlowFn1()
//       getInfo()
//       showLoading.value = false
//     }
//     }

//   },
//   {
//     immediate: true
//   }
// )
const flat: any = ref(false)
watch(
  () => route,
  () => {
    if (route.query.flat) flat.value = route.query.flat
    if (route.name == 'selfdetailMakeMenu') {
      if (props.id) {
        form.itemsStaging.subItemCode = null
        form.itemsStaging.assetCode = null
        form.itemsStaging.firstLevelCode = null
        form.itemsStaging.secondLevelCode = null
        form.itemsStaging.threeLevelCode = null
        form.itemsStaging.fourthLevelCode = null
        form.itemsStaging.fifthLevelCode = null
        form.itemsStaging.sixthLevelCode = null
        showLoading.value = true
        getFlowFn1()
        getInfo()
        showLoading.value = false
      }
    }
    if (route.query.flat && dispatchInfo.value.workflowInfoVo.status == '审批中')
      flat.value = route.query.flat
    else flat.value = false
  },
  { deep: true, immediate: true }
)
const columns1: DataTableColumns = [
  {
    title: '类型',
    key: 'type',
    width: 50
  },
  {
    title: '人员',
    key: 'userName',
    width: 50
  },
  {
    title: '时间',
    key: 'time',
    width: 100
  },
  {
    title: '结果',
    key: 'result',
    width: 50
  },
  {
    title: '备注',
    key: 'remark',
    width: 150
  }
]
// onMounted(async () => {
//   // 修改回显
//   if (props.id) {
//     getInfo()
//   }
// })
// 获取详情
const dispatchInfo = ref<any>({})
const tableData: any = ref([])
</script>

<template>
  <DetailFormProvider>
  <div class="main">
    <div class="form_content">
      <NScrollbar>
        <NSpin :show="showLoading">
          <div class="content">
            <VDisOrEnd
              v-if="flat"
              :id="form?.fromId"
              :assigneeFlag="form?.assigneeFlag"
              title="编目审核单"
            ></VDisOrEnd>
            <!-- 去掉项目中所有的套组 -->
            <!-- <div class="topTitle">套组</div>
            <NSpace :key="i.id" v-for="i in GroupList">
              <NFormItem label="题名" path="">
                <n-tooltip trigger="hover">
                  <template #trigger>
                    <NInput :value="i.itemName" class="inputGroup" disabled />
                  </template>
                  {{ i.itemName }}
                </n-tooltip>
              </NFormItem>
              <NFormItem label="资产码" path="">
                <NInput :value="i.assetCode" class="inputGroup" disabled />
              </NFormItem>
              <NFormItem label="流水号" path="serialNumber">
                <NInput :value="i.serialNumber" class="inputGroup" disabled />
              </NFormItem>
              <NFormItem label="排架号" path="time">
                <NInput :value="i.shelfNumber" class="inputGroup" disabled />
              </NFormItem>
            </NSpace> -->
            <!-- <div class="topTitle">基本信息</div> -->
            <!-- <BasicInfo :id="props.idSelf" :code="props.idSelf"></BasicInfo> -->
            <div class="dynamic-form-demo">
          <DynamicFormComponent ref="dfInst" v-if='formData1.BMCOM003' :disabled="true" :data="formData1" :createVars="createVars" />
        </div>
            <!-- <DynamicPageForm ref="formInst" :form-model="otherJson" :model="formData1" disabled :form-data="formData1"
              label-placement="left" require-mark-placement="left" label-width="140" /> -->
            <div class="detailinlineStyle">
              <span v-if='fileImgList?.length > 0' style='margin-right:10px'>附件:</span>
              <div>
                <n-image-group>
                  <n-space>
                    <n-image width="100" height="100" :src="i.url" :key="i.id" v-for="i in fileImgList" />
                  </n-space>
                </n-image-group>
              </div>
            </div>
            <div>
              <div class="topTitle">审批信息</div>
              <div class="approve">
                <div class="box">
                  <span>审批状态</span>
                  <span>{{ form?.status }}</span>
                </div>
                <div class="box">
                  <span>审批流程</span>
                  <span>{{ form?.workflow || '--' }}</span>
                </div>
              </div>
              <div class="topTitle">审批记录</div>
              <div class="table">
                <NDataTable
                  :bordered="false"
                  :columns="columns1"
                  :data="tableData1"
                  :pagination="false"
                  striped
                />
              </div>
            </div> 
              <!-- 终审显示 -->
            <!-- <div v-if="showEnd">
              <div class="topTitle">终审信息</div>
              <div class="approve">
                <div class="box">
                  <span>审批状态</span>
                  <span>{{ form?.status1 }}</span>
                </div>
                <div class="box">
                  <span>审批流程</span>
                  <span>{{ form?.workflow1 || '--' }}</span>
                </div>
              </div>
              <div class="topTitle">终审记录</div>
              <div class="table">
                <NDataTable :bordered="false" :columns="columns1" :data="tableData2" :pagination="false" striped />
              </div>
            </div> -->
            <!-- <div class="approve" style="margin-top: 10px">
              <div class="box" v-if="endBackShow">
                <span>状态</span>
                <span>终审退回</span>
              </div>
            </div> -->
            <!-- <div class="topTitle" v-if="inputShow">
              入库位置
            </div>
            <NForm :model="form" ref="userFormRef" label-placement="left" label-width="140rem"
              require-mark-placement="left" v-if="inputShow">
              <NSpace>
                <NFormItem label="入库位置:" path="itemsStaging.firstLevelCode">
                  <NSelect v-model:value="form.itemsStaging.firstLevelCode" placeholder="位置1" class="inputWHmin"
                    filterable clearable :disabled="props?.typeShow == 1" />
                </NFormItem>
                <NFormItem label="" path="itemsStaging.secondLevelCode">
                  <NSelect v-model:value="form.itemsStaging.secondLevelCode" placeholder="位置2" class="inputWHmin"
                    filterable clearable :disabled="props?.typeShow == 1" />
                </NFormItem>
                <NFormItem label="" path="itemsStaging.threeLevelCode">
                  <NSelect v-model:value="form.itemsStaging.threeLevelCode" placeholder="位置3" class="inputWHmin"
                    filterable clearable :disabled="props?.typeShow == 1" />
                </NFormItem>
                <NFormItem label="" path="itemsStaging.fourthLevelCode">
                  <NSelect v-model:value="form.itemsStaging.fourthLevelCode" placeholder="位置4" class="inputWHmin"
                    filterable clearable :disabled="props?.typeShow == 1" />
                </NFormItem>
                <NFormItem label="" path="itemsStaging.fifthLevelCode">
                  <NSelect v-model:value="form.itemsStaging.fifthLevelCode" placeholder="位置5" class="inputWHmin"
                    filterable clearable :disabled="true" />
                </NFormItem>
                <NFormItem label="" path="itemsStaging.sixthLevelCode">
                  <NSelect v-model:value="form.itemsStaging.sixthLevelCode" placeholder="位置6" class="inputWHmin"
                    filterable clearable :disabled="true" />
                </NFormItem>
              </NSpace>
            </NForm> -->
          </div>
        </NSpin>
      </NScrollbar>
    </div>
  </div>
</DetailFormProvider>
  <FixedAction>
    <NSpace justify="center">
      <NButton
        style="width: 78px"
        ghost
        @click="goBack"
      >
        取消
      </NButton>
      <!-- <NButton type="primary" style="width: 78px" @click="submit" :loading="loading" v-if="props?.typeShow == 0">
        确定
      </NButton> -->
    </NSpace>
  </FixedAction>
</template>
<style scoped lang="scss">
@mixin CommonFont {
  font-size: 18rem;
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;
  color: #333333;
}

.main {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  overflow: hidden;
  .dynamic-form-demo {
    background-color: #e1e1e1;
    padding: 30px 45px 10px;
    // height:300px;
  }
  .form_content {
    width: 100%;
    height: 100%;
    padding: 20rem 20rem 0;

    .topTitle {
      font-size: 22px;
      font-family: PingFangSC, PingFang SC;
      font-weight: 500;
      color: #5fb17f;
      margin-bottom: 10rem;
    }

    .inputWH {
      flex: 1;
    }

    .inputWHmin {
      width: 150rem;
    }

    .content {
      display: flex;
      flex-direction: column;
      width: 100%;
      height: 100%;
      padding: 18rem 33rem 120rem;
      overflow-y: scroll;
      background-color: #ebeceb;
      @include CommonFont;
    }
  }

  .approve {
    display: flex;
    width: 100%;
    margin-bottom: 20rem;
    border-bottom: 1px dashed #bc9e70;

    .box {
      display: flex;
      flex-direction: column;
      justify-content: center;
      min-width: 100rem;
      width: auto;
      height: 90rem;
      border-radius: 4px;
      border: 1px solid #d9d9d9;
      padding: 12rem;
      margin-right: 10rem;
      margin-bottom: 20rem;

      span:first-child {
        font-size: 16rem;
      }

      span:last-child {
        font-weight: 500;
        color: #5fb17f;
      }
    }
  }
}

// .ac-card {
//     padding: 20rem;
//     background-color: #e1e1e1;
//   }

.content::-webkit-scrollbar {
  display: none;
}

.detailinlineStyle {
  display: flex;
  width: 100%;
  margin-bottom: 20px;
  margin-left: 20px;
  margin-top: 20px;
  // span:nth-child(1) {
  //   width: 150px;
  //   text-align: right;
  //   margin-right: 20px;
  // }
  // span:nth-child(2) {
  //   width: 150px;
  //   text-align: left;
  //   margin-right: 250px;
  // }
  // span:nth-child(3) {
  //   width: 50px;
  //   text-align: left;
  //   margin-right: 10px;
  // }
}

:deep(.n-spin-container) {
  width: 100%;
  height: 100%;
}

:deep(.n-scrollbar-container) {
  width: 100%;
  height: 100%;
}

:deep(.n-scrollbar-content) {
  width: 100%;
  height: 100%;
}

:deep(.n-spin-content) {
  width: 100%;
  height: 100%;
}
</style>
